package p.ithorns.tools.translator.sdk.handler;

import com.google.auto.service.AutoService;
import org.springframework.util.StringUtils;
import p.ithorns.tools.translator.annotation.field.MapField;
import p.ithorns.tools.translator.annotation.Translator;

import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * MapTransformer
 *
 * Translator最佳实践: 直接定义本地Map字典(在字段上直接提供)
 *
 * @author Ht.L
 * @date 2024-05-25 22:33
 * @since 1.0.0
 */
@AutoService(Translator.class)
public class MapTranslator implements Translator<String, MapField> {

    @Override
    public String translate(MapField annotation, String value) {
        Map<String, String> map = toMap(annotation.map());
        return Optional.ofNullable(map.get(value)).orElse("");
    }

    public Map<String, String> toMap(String[] arr) {
        // String[] arr =  {"1:A", "2:B", "3:C"};
        Map<String, String> map = new HashMap<>();
        for (String s : arr) {
            String trim = StringUtils.trimAllWhitespace(s);
            String[] split = StringUtils.split(trim, ":");
            if (null != split && split.length == 2) {
                map.put(split[0], split[1]);
            }
        }
        return map;
    }

    private String[] split(@NotNull String toSplit) {
        final String s = trimAllWhitespace(toSplit);
        if (isBlank(s)) {
            return new String[0];
        }
        return s.split(",");
    }

    private boolean isBlank(CharSequence cs) {
        int strLen;
        if (cs != null && (strLen = cs.length()) != 0) {
            for (int i = 0; i < strLen; ++i) {
                if (!Character.isWhitespace(cs.charAt(i))) {
                    return false;
                }
            }
        }
        return true;
    }

    private String trimAllWhitespace(String src) {
        if (!hasLength(src)) {
            return "";
        } else {
            int len = src.length();
            StringBuilder sb = new StringBuilder(src.length());

            for (int i = 0; i < len; ++i) {
                char c = src.charAt(i);
                if (!Character.isWhitespace(c)) {
                    sb.append(c);
                }
            }

            return sb.toString();
        }
    }

    private boolean hasLength(String src) {
        return src != null && !src.isEmpty();
    }

}